﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QuailDb;
using System.Text.RegularExpressions;

namespace QuailDashboard.View.Web
{
    public partial class Preview : System.Web.UI.Page
    {
        private static readonly Regex YsodMessageRegex =
                                new Regex(
                                    @"^YSOD found on http://.+/error\.aspx\?errorGuid=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$");

        protected void Page_Load(object sender, EventArgs e)
        {
            var id = Request.QueryString["entryid"];
            string result;

            if (!string.IsNullOrEmpty(id))
            {
                int testruntasklogentryid;
                if (int.TryParse(id, out testruntasklogentryid))
                {
                    using (var db = new QuailObjectContextConnection())
                    {
                        var found = (from logentries in db.Context.TestRunTaskLogEntries
                                     from tasklog in db.Context.TestRunTasks
                                     from testrun in db.Context.TestRuns
                                     from testenv in db.Context.TestEnvironments
                                     where logentries.TestRunTaskId == tasklog.TestRunTaskId
                                           && logentries.TestRunTaskLogEntryId == testruntasklogentryid
                                           && tasklog.TestRunId == testrun.TestRunId
                                           && testrun.TestEnvironmentId == testenv.TestEnvironmentId
                                     select new {tasklog.TaskName, logentries.EntryText, testenv.EnvironmentName}).FirstOrDefault();

                        if (found != null)
                        {
                            var idx = found.EntryText.IndexOf("<head");
                            if (idx == -1)
                                idx = found.EntryText.IndexOf("<body");

                            if (idx >= 0)
                            {
                                result = "<html>" + found.EntryText.Substring(idx) + "</html>";
                            }
                            else
                            {
                                // if it's a ysod message, add a link to see the ysod in the toolbox
                                var match = YsodMessageRegex.Match(found.EntryText);
                                if (match.Success)
                                {
                                    // we need to figure out the environment for the ysod query string
                                    string envArg;
                                    var envName = found.EnvironmentName.ToLower();
                                    if (envName.StartsWith("prod"))
                                        envArg = "P";
                                    else if (envName.StartsWith("uat"))
                                        envArg = "UAT";
                                    else if (envName.StartsWith("qa"))
                                        envArg = "QA";
                                    else
                                        envArg = "Dev";

                                    result = found.EntryText +
                                             "<br><a href='http://toolbox/SajSystemConfig/Audit/Search?q=" +
                                             match.Groups[1] + "&Env=" + envArg +
                                             "&l=&m=&ErrorClass=All&Timeout=60'>Click to view error in toolbox</a>";
                                }
                                else
                                {
                                    result = found.EntryText;
                                    if (result.StartsWith("<?xml"))
                                    {
                                        Response.ContentType = "text/xml";
                                    }
                                }
                            }

                            // result = "<html><head><title>Log Entry Contents: " + HttpUtility.HtmlEncode(found.TaskName) + "</title><body>Result of Task: " + HttpUtility.HtmlEncode(found.TaskName) + "<br><frame"
                        }
                        else
                            result = GetErrorHtml("Error", "Unable to locate entryid in database");
                    }
                }
                else
                {
                    result = GetErrorHtml("Error", "Invalid entryid parameter passed to page");
                }
            }
            else
                result = GetErrorHtml("Error", "Missing entryid parameter passed to page");

            Response.Write(result);
        }

        private string GetErrorHtml(string title, string error)
        {
            return "<html><title>" + title + "</title><body>" + error + "</body></html>";
        }
    }
}
